<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>作业</title>

    <link href="/assets/images/favicon.ico" rel="icon">
    <link rel="stylesheet" href="/assets/libs/layui/css/layui.css" />
    <link rel="stylesheet" href="/assets/module/admin.css?v=318" />
    <link rel="stylesheet" href="/viewer/viewer.min.css">


    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="/assets/libs/layui/layui.js"></script>
    <script type="text/javascript" src="/assets/js/common.js?v=318"></script>
    <script type="text/javascript" src="/viewer/viewer.min.js"></script>
    <style>
        .model-form-footer {
            margin-top: 10px;
            text-align: center;
        }

        #imageContainer {
            margin: 0;
            display: flex;
            flex-wrap: wrap; /* 允许换行 */
        }

        /* 设置图片的大小 */
        .image-preview {
            width: 100px; /* 设置图片宽度 */
            height: 100px; /* 高度自动调整，保持图片比例 */
            margin: 5px; /* 设置图片之间的间距 */
            border: 1px solid rgba(66, 66, 66, 0.5); /* 添加黑色边框 */
            border-radius: 10px; /* 设置圆角半径 */
        }

        .image-view{
            margin: 0;
        }

        .file-view {
            max-width: 300px;
            margin-bottom: 5px;
        }

        .file-box {
            display: block;
            border: 1px solid #ddd; /* 边框 */
            padding: 10px;
            text-align: left;
            color: #333;
            text-decoration: none; /* 去掉链接下划线 */
            border-radius: 4px; /* 圆角 */
            transition: background-color 0.3s ease; /* 鼠标悬停效果 */
        }

        .file-box:hover {
            background-color: #f5f5f5; /* 鼠标悬停背景色 */
        }

        .file-name {
            word-break: break-all; /* 文件名过长时自动换行 */
        }
    </style>
</head>

<body>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">

            <form class="layui-form model-form" id="homeworkCorrectForm" th:object="${model}">
                <input type="hidden" name="id" th:field="*{id}" />
                <input type="hidden" id="homewrok" th:field="*{homeworkId}" />
                <input type="hidden" id="isRead" th:field="*{isRead}" />
                <!-- 学生姓名（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">学生</label>
                    <div class="layui-input-block">
                        <input type="text" th:field="${model.student.name}" disabled class="layui-input" />
                    </div>
                </div>
                <!-- 题目要求（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">题目要求</label>
                    <div class="layui-input-block">
                        <input type="text" th:field="${model.homework.title}" disabled class="layui-input" />
                    </div>
                </div>

                <!-- 作业类型（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">作业类型</label>
                    <div class="layui-input-block">
                        <input type="text" th:field="${model.homework.homeworkType}" disabled class="layui-input" />
                    </div>
                </div>

                <!-- 开始时间（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-block">
                        <input type="text" th:value="${#dates.format(model.homework.beginDate, 'yyyy-MM-dd HH:mm:ss')}" disabled class="layui-input" />
                    </div>
                </div>

                <!-- 结束时间（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-block">
                        <input type="text" th:value="${#dates.format(model.homework.endDate, 'yyyy-MM-dd HH:mm:ss')}" disabled class="layui-input" />
                    </div>
                </div>
                <!-- 提交时间（只显示，不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">提交时间</label>
                    <div class="layui-input-block">
                        <input type="text" th:value="${#dates.format(model.submitDate, 'yyyy-MM-dd HH:mm:ss')}" disabled class="layui-input" />
                    </div>
                </div>
                <!-- 作业内容（不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">作答详情</label>
                    <div class="layui-input-block">
                        <textarea id="contentTextarea" th:field="*{content}" disabled class="layui-textarea"></textarea>
                    </div>
                </div>
                <!-- 文件内容（不可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">上传图片</label>
                    <!-- 遍历展示图片 -->
                    <div id="imageContainer">
                        <div class="layui-input-block image-view" th:each="imageName : ${model.imageNames}">
                            <img height="50%" width="50%" th:src="${imageName}" class="image-preview" alt="图片">
                        </div>
                    </div>

                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">上传文件</label>
                    <div class="layui-input-block file-view" th:each="fileName : ${model.fileNames}">
                        <a th:href="${fileName}" class="file-box" >
                            <div class="file-name" th:data-filename="${fileName}"></div>
                        </a>
                    </div>
                </div>

                <!-- 分数（可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">分数</label>
                    <div class="layui-input-block">
                        <!-- 如果 score 为 null 或 0，则输入框显示为空 -->
                        <input type="number" id="score" th:field="*{score}" class="layui-input" th:value="${score != null && score != 0 ? score : ''}" />
                    </div>
                </div>
                <!-- 评语（可编辑） -->
                <div class="layui-form-item">
                    <label class="layui-form-label">评语</label>
                    <div class="layui-input-block">
                        <textarea id="comment" th:field="*{comment}" class="layui-textarea"></textarea>
                    </div>
                </div>

                <!-- 提交按钮 -->
                <div class="layui-form-item text-center model-form-footer">
                    <button class="layui-btn" lay-filter="save" lay-submit>保存</button>
                    <button type="button" class="layui-btn layui-btn-primary" lay-event="closeDialog">关闭</button>
                </div>
            </form>
            <script src="/assets/libs/jquery/jquery-3.2.1.min.js"></script>
            <script>
                $(function () {
                    layui.use(['form', 'layer', 'laydate'], function () {
                        var form = layui.form;
                        var layer = layui.layer;
                        var laydate = layui.laydate;
                        var $ = layui.jquery;
                        var index = parent.layer.getFrameIndex(window.name);
                        var chargerName = parent.chargerName;

                        // 获取文本域元素
                        var contentTextarea = document.getElementById('contentTextarea');
                        // 获取 content 对应的 JSON 字符串数据（假设绑定后能获取到值，实际可能需调整）
                        var contentJsonStr = $('#contentTextarea').val();
                        try {
                            var contentObj = JSON.parse(contentJsonStr);
                            // 显示解析后的文本内容
                            contentTextarea.value = contentObj.text;
                        } catch (e) {
                            console.log('解析 JSON 字符串出错：', e);
                        }

                        function showLarge(src) {

                            // 创建容器
                            const imgContainer = document.createElement('div');
                            imgContainer.innerHTML = `<img src="${src}" alt="图片" style="max-width: 90vw; max-height: 90vh; object-fit: contain;">`;
                            document.body.appendChild(imgContainer);

                            // 创建 Viewer 实例
                            const viewer = new Viewer(imgContainer, {
                                inline: false,
                                toolbar: {
                                    zoomIn: true,
                                    zoomOut: true,
                                    oneToOne: true,
                                    reset: true,
                                    rotateLeft: true,
                                    rotateRight: true,
                                    flipHorizontal: true,
                                    flipVertical: true
                                },
                                initialViewIndex: 0, // 默认显示第一张图片
                                zoomRatio: 0.5, // 调整缩放速度
                                navbar: false // 是否显示导航栏
                            });

                            // 打开 Viewer
                            viewer.show();

                            // 关闭时销毁实例，防止内存泄漏
                            viewer.hide = function () {
                                viewer.destroy();
                                document.body.removeChild(imgContainer);
                            };
                        }

                        // 为图片绑定点击事件
                        $('.image-preview').on('click', function () {
                            var src = $(this).attr('src');
                            showLarge(src);
                        });

                        function validateForm() {
                            var score = $("#score").val();
                            if (score === "") {
                                layer.msg("请填写分数", {
                                    icon: 2,
                                    anim: 6
                                });
                                return false;
                            }
                            return true;
                        }

                        // 页面加载后，如果 score 为 0 则清空输入框
                        window.onload = function () {
                            var scoreInput = document.getElementById('score');
                            if (scoreInput.value === '0') {
                                scoreInput.value = '';
                            }
                        }

                        // 监听保存按钮提交事件
                        form.on('submit(save)', function () {
                            var loadIndex = layer.load(2);
                            if (!validateForm()) {
                                layer.close(loadIndex);
                                return false;
                            }
                            var score = $("#score").val();
                            var comment = $("#comment").val();
                            var id = $("input[name='id']").val();
                            var homeworkId = $("#homewrok").val();
                            var readDate = new Date(getFormattedCurrentTime()).toISOString();

                            var formDataObj = {
                                id: id,
                                score: score,
                                homeworkId: homeworkId,
                                comment: comment,
                                readDate: readDate
                            };

                            $.ajax({
                                type: 'POST',
                                url: "/homeworkdetail/save",
                                contentType: 'application/json',
                                data: JSON.stringify(formDataObj),
                                dataType: 'json',
                                success: function (res) {
                                    layer.close(loadIndex);
                                    if (res.code === 0) {
                                        // 触发父窗口的搜索刷新表格
                                        $('#search', parent.document).click();
                                        // 关闭当前弹出层
                                        parent.layer.close(index);
                                        parent.layer.msg('批阅成功', { icon: 1 });
                                    } else {
                                        layer.msg('批阅失败: ' + res.msg, { icon: 2 });
                                    }
                                },
                                error: function () {
                                    layer.close(loadIndex);
                                    layer.msg('网络错误，请稍后再试', { icon: 2 });
                                }
                            });
                            return false;
                        });

                        // 修改下载按钮点击事件，直接跳转下载链接
                        $('#downloadBtn').on('click', function () {
                            var id = $("input[name='id']").val();
                            window.location.href = "/homeworkdetail/downloadFiles?id=" + id;
                        });

                        // 获取格式化当前时间的函数
                        function getFormattedCurrentTime() {
                            var currentTime = new Date();
                            return currentTime.getFullYear() + '-' +
                                (currentTime.getMonth() + 1).toString().padStart(2, '0') + '-' +
                                currentTime.getDate().toString().padStart(2, '0') + ' ' +
                                currentTime.getHours().toString().padStart(2, '0') + ':' +
                                currentTime.getMinutes().toString().padStart(2, '0') + ':' +
                                currentTime.getSeconds().toString().padStart(2, '0');
                        }

                        // 关闭按钮事件
                        $('.layui-btn-primary').on('click', function () {
                            parent.layer.close(index);
                        });
                    });
                });

                document.addEventListener("DOMContentLoaded", function () {
                    document.querySelectorAll(".file-name").forEach(link => {
                        let fileName = link.getAttribute("data-filename");

                        // 取出最后的文件名部分（去掉路径）
                        fileName = fileName.substring(fileName.lastIndexOf('/') + 1);

                        // 去掉 UUID（格式：xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx_）
                        fileName = fileName.replace(/^[\da-f]{8}-(?:[\da-f]{4}-){3}[\da-f]{12}_/, '');

                        // 去掉时间戳（格式：-数字.扩展名，确保保留扩展名）
                        fileName = fileName.replace(/-\d+\./, '.');

                        // 设置修改后的文件名
                        link.textContent = fileName;
                    });
                });
            </script>

        </div>
    </div>
</div>

<footer>
    <!-- JS 部分 -->
    <script type="text/javascript">
        var url = window.location.pathname.substring(1);
        var item = url.split("/");
        var jsUrl = "/static/module/javaweb_" + item[0] + ".js";
        document.write("<script src='" + jsUrl + "'><\/script>");
    </script>
</footer>
</body>
</html>